import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'

export interface TagView {
  name: string
  path: string
  title: string
  fullPath: string
  query?: Record<string, any>
  params?: Record<string, any>
  meta?: Record<string, any>
}

export const useTagsViewStore = defineStore(
  'tagsView',
  () => {
    // 访问过的视图
    const visitedViews = ref<TagView[]>([])
    
    // 缓存的视图
    const cachedViews = ref<string[]>([])

    // 添加访问过的视图
    const addVisitedView = (route: RouteLocationNormalized) => {
      if (visitedViews.value.some(v => v.path === route.path)) return
      
      const view: TagView = {
        name: route.name as string,
        path: route.path,
        title: (route.meta?.title as string) || '未知页面',
        fullPath: route.fullPath,
        query: route.query,
        params: route.params,
        meta: route.meta,
      }
      
      visitedViews.value.push(view)
    }

    // 添加缓存视图
    const addCachedView = (route: RouteLocationNormalized) => {
      if (route.name && !cachedViews.value.includes(route.name as string)) {
        if (route.meta?.keepAlive) {
          cachedViews.value.push(route.name as string)
        }
      }
    }

    // 删除访问过的视图
    const delVisitedView = (view: TagView) => {
      return new Promise<TagView[]>(resolve => {
        for (const [i, v] of visitedViews.value.entries()) {
          if (v.path === view.path) {
            visitedViews.value.splice(i, 1)
            break
          }
        }
        resolve([...visitedViews.value])
      })
    }

    // 删除缓存视图
    const delCachedView = (view: TagView) => {
      return new Promise<string[]>(resolve => {
        const index = cachedViews.value.indexOf(view.name)
        if (index > -1) {
          cachedViews.value.splice(index, 1)
        }
        resolve([...cachedViews.value])
      })
    }

    // 删除其他访问过的视图
    const delOthersVisitedViews = (view: TagView) => {
      return new Promise<TagView[]>(resolve => {
        visitedViews.value = visitedViews.value.filter(v => {
          return v.meta?.affix || v.path === view.path
        })
        resolve([...visitedViews.value])
      })
    }

    // 删除其他缓存视图
    const delOthersCachedViews = (view: TagView) => {
      return new Promise<string[]>(resolve => {
        const index = cachedViews.value.indexOf(view.name)
        if (index > -1) {
          cachedViews.value = cachedViews.value.slice(index, index + 1)
        } else {
          cachedViews.value = []
        }
        resolve([...cachedViews.value])
      })
    }

    // 删除所有访问过的视图
    const delAllVisitedViews = () => {
      return new Promise<TagView[]>(resolve => {
        visitedViews.value = visitedViews.value.filter(tag => tag.meta?.affix)
        resolve([...visitedViews.value])
      })
    }

    // 删除所有缓存视图
    const delAllCachedViews = () => {
      return new Promise<string[]>(resolve => {
        cachedViews.value = []
        resolve([...cachedViews.value])
      })
    }

    // 更新访问过的视图
    const updateVisitedView = (view: TagView) => {
      for (let v of visitedViews.value) {
        if (v.path === view.path) {
          v = Object.assign(v, view)
          break
        }
      }
    }

    // 添加视图（同时添加到访问过的和缓存的）
    const addView = (route: RouteLocationNormalized) => {
      addVisitedView(route)
      addCachedView(route)
    }

    // 删除视图（同时从访问过的和缓存的删除）
    const delView = (view: TagView) => {
      return new Promise<{ visitedViews: TagView[]; cachedViews: string[] }>(resolve => {
        Promise.all([delVisitedView(view), delCachedView(view)]).then(([visitedViews, cachedViews]) => {
          resolve({ visitedViews, cachedViews })
        })
      })
    }

    // 删除其他视图
    const delOthersViews = (view: TagView) => {
      return new Promise<{ visitedViews: TagView[]; cachedViews: string[] }>(resolve => {
        Promise.all([delOthersVisitedViews(view), delOthersCachedViews(view)]).then(
          ([visitedViews, cachedViews]) => {
            resolve({ visitedViews, cachedViews })
          }
        )
      })
    }

    // 删除所有视图
    const delAllViews = () => {
      return new Promise<{ visitedViews: TagView[]; cachedViews: string[] }>(resolve => {
        Promise.all([delAllVisitedViews(), delAllCachedViews()]).then(([visitedViews, cachedViews]) => {
          resolve({ visitedViews, cachedViews })
        })
      })
    }

    return {
      visitedViews,
      cachedViews,
      addVisitedView,
      addCachedView,
      delVisitedView,
      delCachedView,
      delOthersVisitedViews,
      delOthersCachedViews,
      delAllVisitedViews,
      delAllCachedViews,
      updateVisitedView,
      addView,
      delView,
      delOthersViews,
      delAllViews,
    }
  },
  {
    persist: {
      key: 'kexilo-tags-view',
      storage: sessionStorage,
      paths: ['visitedViews'],
    },
  }
)
